import { CheckAns } from "./CheckAns";

namespace LeetCode0414ThirdMaxNum {

    function thirdMax(nums: number[]): number {
        // 定长数组便于拓展
        const len = 3;
        let ary: number[] = [];
        // 题设输入数据length>1,此处不作空数组检查
        for (const num of nums) {
            for (let i = 0; i < len; i++) {
                // 题设要求相同的算一个
                if (num == ary[i])
                    break;
                // 新的输入填入
                if (ary[i] == undefined || num > ary[i]) {
                    for (let j = len - 1; j > i; j--) {
                        if (ary[j - 1] != undefined)
                            ary[j] = ary[j - 1];
                    }
                    ary[i] = num;
                    break;
                }
            }
        }
        return ary[len - 1] != undefined ? ary[len - 1] : ary[0];
    };

    // test
    const testData: { nums: number[], ans: number }[] = [
        { nums: [3, 2, 1], ans: 1 },
        { nums: [1, 2], ans: 2 },
        { nums: [2, 2, 3, 1], ans: 1 }
    ];
    for (const data of testData) {
        const ans = thirdMax(data.nums);
        CheckAns(data, ans);
    }

}